import axios from 'axios'
import { getItem, removeItem } from 'utils/storage'
import { message } from 'antd'
import history from './history'
const instance = axios.create({
  baseURL: 'http://liufusong.top:8888/',
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (getItem()) {
      config.headers.Authorization = `Bearer ${getItem()}`
    }

    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    if (response.data.code === 401) {
      message.error('token过期')
      history.push('login')
      removeItem()
      return Promise.reject(new Error('401'))
    }
    return response.data
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default instance
